package ar.edu.unq.tpi.uis.tepe3.wicket;

import org.apache.wicket.protocol.http.WebApplication;
import org.apache.wicket.settings.IResourceSettings;
import org.apache.wicket.util.resource.locator.IResourceStreamLocator;

import com.db4o.ObjectSet;

import ar.edu.unq.tpi.uis.tepe3.dominio.SvnManager;
import ar.edu.unq.tpi.uis.tepe3.dominio.exception.PersistenceException;
import ar.edu.unq.tpi.uis.tepe3.dominio.persistence.Db4oPersistence;
import ar.edu.unq.tpi.uis.tepe3.wicket.pages.DashboardPage;

/**
 * Application object for your web application. If you want to run this application without deploying, run the Start class.
 * 
 * @see wicket.myproject.Start#main(String[])
 */
public class WicketApplication extends WebApplication
{    

	private Db4oPersistence persistence;
	private SvnManager model;
	
	@Override
	protected void init() {
		super.init();

		// the full path to your folder, relative to the context root
		//this.getResourceSettings().addResourceFolder("pages");

		IResourceSettings resourceSettings = getResourceSettings();
		resourceSettings.addResourceFolder("pages");
		resourceSettings.setResourceStreamLocator((IResourceStreamLocator) new PathStripperLocator());
	}

	
	/**
	 * @see wicket.Application#getHomePage()
	 */
	public Class getHomePage()
	{
		return DashboardPage.class;
	}

	private void setPersistence(Db4oPersistence persistence) {
		this.persistence = persistence;
	}

	private Db4oPersistence getPersistence() {
		return persistence;
	}
	
	public void save() throws PersistenceException{
		this.getPersistence().save(getModel());
	}
	
	public SvnManager getModel(){
		setPersistence(Db4oPersistence.getInstance());
		ObjectSet<SvnManager> results = getPersistence().fetchAll();
		if (results.size() == 0){
			try {
				this.getPersistence().save(new SvnManager());
			} catch (PersistenceException e) {
				e.printStackTrace();
			}
			results = getPersistence().fetchAll();
		}
		setModel(results.next()); // Solo tomo uno, nunca deberia haber mas de uno.
		//getPersistence().close();
		return model;
		
	}

	private void setModel(SvnManager model) {
		this.model = model;
	}
	
	

	
}
